using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Raxxla.DayBreak.Core
{
    /// <summary>
    /// Safe multithreaded singleton pattern
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class Singleton<T> where T : class, new()
    {
        private static object _internalSyncObject;
        private static T _instance;

        private static Object InternalSyncObject
        {
            get
            {
                if (_internalSyncObject == null)
                {
                    Object obj = new Object();
                    Interlocked.CompareExchange(ref _internalSyncObject, obj, null);
                }
                return _internalSyncObject;
            }
        }

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (InternalSyncObject)
                    {
                        // Do not use lock(typeof(MyClass)) 
                        if (_instance == null)
                        {
                            T tmp = new T();
                            // Do all initialization before publishing
                            _instance = tmp;
                        }
                    }
                }
                return _instance;
            }
        }
    }
}
